#! /usr/bin/env python3

import sys
import os
import sqlite3
from flask import Flask, render_template

database = 'static/base/video.db'
videopath = 'static/video/'

### file ###################################################
def get_os_video():
    L = []
    for root, dirs, files in os.walk(videopath):
        for f in files:
            if os.path.splitext(f)[1] == '.mp4': # split file.extension
                L.append(os.path.join(root, f).split(videopath)[1])
    return L

### SQL ####################################################
def remove_base():
    if os.path.exists(database):
        os.remove(database)
        print('remove: ' + database)

def create_base():
    status = False
    base = sqlite3.connect(database)
    c = base.cursor()
    try:
        c.execute('CREATE TABLE VIDEO \
                (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL);')
        status = True
    except Exception as e:
        print(e)
        status = False
    base.commit()
    base.close()
    return status

def insert_base(name):
    base = sqlite3.connect(database)
    c = base.cursor()
    try:
        c.execute('INSERT INTO VIDEO (NAME) VALUES (\'%s\');' % name)
    except Exception as e:
        print(e)
    base.commit()
    base.close()

def select_base():
    L = []
    base = sqlite3.connect(database)
    c = base.cursor()
    try:
        L = c.execute('SELECT * from VIDEO')
    except Exception as e:
        print(e)
    L = c.fetchall()
    base.commit()
    base.close()
    return L

def insert_video():
    for video in get_os_video():
        insert_base(video)
        print("insert: " + video);

def select_video():
    for video in select_base():
        print(video)

### parser #################################################
def parser(args=[]):
    print("parse []", *args)
    if args[1] == 'init':
        if create_base():
            insert_video()
    if args[1] == 'select':
        L = select_base()
        print(L)
    if args[1] == 'clean':
        remove_base()

### flask #################################################
app = Flask(__name__)

@app.route('/video/<vstr>')
def vsfa(vstr): # get video by id
    index = int(vstr[1:]) - 1
    video = select_base()
    return render_template('vsfa.html', video=video, index=index)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    if len(sys.argv) > 1:
        parser(sys.argv)
        exit()
    app.run(host='0.0.0.0', port=5000, debug=True)

